package com.py.gs.businese.unionbattletest;

/**
 * 500, 50, 10000
 * 循环跑10次battle
 * 
10次总耗时:350ms
10次总对战次数:45047415
 * 
 * @author cyd
 * @date 2018年4月19日
 */
public class UnionBattleService2 extends UnionBattleService {
	
	public UnionBattleService2(int unionNum, int ministerNum, int powerBound) {
		super(unionNum, ministerNum, powerBound);
	}
	
	protected boolean battle(UnionBattleInfo attack, UnionBattleInfo defend) {
		if (attack.ministers.size() == 0) {
			return false;
		}
		if (defend.ministers.size() == 0) {
			return true;
		}
		int attackIndex = 0;
		int defendIndex = 0;
		MinisterBattleInfo attackMinister = attack.ministers.get(attackIndex);
		MinisterBattleInfo defendMinister = defend.ministers.get(defendIndex);
		while (true) {//打到自己活着对方没有出战大臣，停止战斗返回战斗结果
			int battleRet = battle(attackMinister, defendMinister);
			if (battleRet < 0) {//攻击方输
				attackMinister.resetPower();
				attackIndex++;
				if (attackIndex == attack.ministers.size()) {
					defendMinister.resetPower();
					return false;
				}
				if (defendMinister.ministerWinCount < 2) {
					defendMinister.ministerWinCount++;
				} else {
					defendMinister.resetPower();
					defendIndex++;
					if (defendIndex == defend.ministers.size()) {
						return true;
					}
					defendMinister = defend.ministers.get(defendIndex);
				}
				attackMinister = attack.ministers.get(attackIndex);
			} else if (battleRet > 0) {//防守方输
				defendMinister.resetPower();
				defendIndex++;
				if (defendIndex == defend.ministers.size()) {
					attackMinister.resetPower();
					return true;
				}
				if (attackMinister.ministerWinCount < 2) {
					attackMinister.ministerWinCount++;
				} else {
					attackMinister.resetPower();
					attackIndex++;
					if (attackIndex == attack.ministers.size()) {
						return false;
					}
					attackMinister = attack.ministers.get(attackIndex);
				}
				defendMinister = defend.ministers.get(defendIndex);
			} else {
				attackMinister.resetPower();
				defendMinister.resetPower();
				attackIndex++;
				if (attackIndex == attack.ministers.size()) {
					return false;
				}
				defendIndex++;
				if (defendIndex == defend.ministers.size()) {
					return true;
				}
				attackMinister = attack.ministers.get(attackIndex);
				defendMinister = defend.ministers.get(defendIndex);
			}
		}
	}
	/**
	 * 大臣战斗结果，小于0表示输，大于0表示赢，等于0表示一起死
	 * @param attackMinister
	 * @param defendMinister
	 * @return
	 */
	private int battle(MinisterBattleInfo attackMinister, MinisterBattleInfo defendMinister) {
		battleCount++;
		if (attackMinister.ministerLeftPower > defendMinister.ministerLeftPower) {
			attackMinister.ministerLeftPower -= defendMinister.ministerLeftPower;
			return 1;
		} else if (attackMinister.ministerLeftPower < defendMinister.ministerLeftPower) {
			defendMinister.ministerLeftPower -= attackMinister.ministerLeftPower;
			return -1;
		} else {
			return 0;
		}
	}

}
